const express=require("express")
const app = express();
const md5=require('md5')
const bodyParser=require("body-parser")
const mongodb=require('mongodb')
const request=require("request")
const {getRandom,json,encode,decode,changeArr}=require("../api/fools")
const db=require("../api/module/db")
app.use(express.static(__dirname));
app.use(express.static(__dirname+"/upload"));
app.use(bodyParser.json())

app.get("/sendCode",async function (req,res) {
        const phoneId=req.query.phoneId
        const code=getRandom(100000,999999)
    const userInfo=await db.findOne("userList",{
        phoneId
    })
    if(userInfo){
        //判断短信是否过期
            if(Date.now()-userInfo.sendTime>1000*60){
                db.updateOne("userList",{phoneId},{$set:{code,sendTime:Date.now()}})
                    res.json({
                        ok:1,
                        msg:"发送成功",
                        code
                    })
            }else{
                res.json({
                        ok:-1,
                        msg:"距离获取下一次验证码还有"+(60-Number.parseInt((Date.now()-userInfo.sendTime)/1000))+"秒"
                })
            }
    }else{
        await db.insertOne("userList",{
                phoneId,
                code,
                sendTime: Date.now()
        });
        res.json({
            ok:1,
            msg:"发送成功",
            code
        })
    }
})

app.post("/login",async function (req,res) {
    const {phoneId,code}=req.body
    const userInfo=await db.findOne("userList",{
        phoneId,
        code
    })
    if(userInfo){
        if(Date.now()-userInfo.sendTime>1000*60*5){
            res.json({
                ok:-1,
                msg:"验证码失效"
            })
        }else{
            res.json({
                ok:1,
                msg:"登陆成功",
                phoneId,
                token:encode(phoneId)
            })
        }
    }else{
        res.json({
            ok:-1,
            msg:"验证码错误"
        })
    }
})
app.get("/search",async function (req,res) {
        const keyWord=req.query.keyword
   const shopList=await db.find("shopList",{
        whereObj:{
          shopName:new RegExp(keyWord)
        },
        sortObj:{
            createTime:-1
        }
    })
    res.json({
        ok:1,
        shopList
    })
})
app.get("/shop/:shopId",async function (req,res) {
    const shopId=req.params.shopId
    const shopInfo=await db.findOneById("shopList",shopId)
        res.json({
            ok:1,
            shopInfo
        })
})

app.get("/shopTypeList",async function (req,res) {
    const limit=(req.query.limit ||30)/1
    const arr=await db.find("shopTypeList",{
        limit,
        sortObj:{
            createTime:-1
        }
    })
    res.json({
        ok:1,
        shopTypeList:changeArr(arr)
    })
})

app.get("/shopList/:shopTypeId",async function (req,res) {
    const shopTypeId=mongodb.ObjectId(req.params.shopTypeId)
    const shopList= await db.find("shopList",{
        sortObj:{
            createTime:-1
        },
        whereObj:{
            shopTypeId
        }
    })
    res.json({
        ok:1,
        shopList
    })
})
app.get("/shopList",async function (req,res) {
    let  pageIndex = (req.query.pageIndex || 1)/1;// 当前页
    const whereObj = {};
    let shopName = req.query.shopName || "";
    if(shopName.length > 0){
        whereObj.shopName = new RegExp(shopName);// 按照名字进行模糊搜索。
    }

    let count = await db.count("shopList",whereObj);// 统计文档数量
    let limit = 10;
    let pageSum = Math.ceil(count/limit);
    if(pageSum < 1) pageSum = 1;
    if(pageIndex > pageSum) pageIndex=pageSum;
    if(pageIndex < 1) pageIndex = 1;
    db.find("shopList",{
        sortObj:{
            createTime:-1
        },
        whereObj,
        limit,
        skip:(pageIndex-1)*limit
    }).then(shopList=>{
        setTimeout(()=>{
            res.json({
                ok:1,
                shopList,
                pageIndex,
                pageSum
            })
        },2000)

    })
})



app.all("*",function (req,res,next) {
    const {ok,info,msg}= decode(req.headers.authorization)
    //判断是否解析成功
    if(ok===1){
        next()
    }else{
        json(res,-2,msg)
    }
})

app.listen(8081,function () {
    console.log("success");
})